package com.nowadays.mobile.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;

import com.nowadays.mobile.R;
import com.nowadays.mobile.ui.MainActivity;
import com.nowadays.mobile.utils.ConstsDefine;

public class NotificationService extends Service {

  private static int NOTIFI_ID = 1;
  private NotificationManager nm;
  private static NotificationCompat.Builder builder;

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return new NotificationServiceBinder();
  }

  public class NotificationServiceBinder extends Binder {
    public NotificationService getService() {
      return NotificationService.this;
    }
  }

  public void showNotification() {
    startForeground(NOTIFI_ID, builder.build());
  }

  public void hideNotification() {
    stopForeground(true);
  }

  private NotificationCompat.Builder initBuilder() {
    return new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_notification)
        .setColor(ContextCompat.getColor(this, R.color.primary))
        .setAutoCancel(true)
        .setContentTitle(getString(R.string.app_name))
        .setContentText(getString(R.string.app_describe))
        .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
  }

  public void updateTime(byte state, String time) {
    if (builder == null) {
      return;
    }
    String stateStr = state == ConstsDefine.STATE.FOCUS ? getString(R.string.focus) : getString(R.string.rest);
    builder.setContentText(String.format(getString(R.string.notication_text), stateStr, time));
    nm.notify(NOTIFI_ID, builder.build());
  }

  public void onEnd(int focusTime) {
    if (builder == null) {
      return;
    }
    //停止前台，可以使notification被删除
    hideNotification();
    builder.setContentText(String.format(getString(R.string.focus_end), focusTime));
    nm.notify(NOTIFI_ID, builder.build());
  }

  @Override
  public void onCreate() {
    super.onCreate();
    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder = initBuilder();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    builder = null;
    nm = null;
  }
}
